package com.voxel.sense.infomsg.utils.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import retrofit2.Call;

/**
 * Created by ChenYiYao on 2018/4/18.
 */

public class RetrofitMangerTack {
    private static RetrofitMangerTack mSingle;
    private Map<Class, List<Call>> datas = new HashMap<>();

    private RetrofitMangerTack() {

    }

    public static synchronized RetrofitMangerTack getInstanse() {
        if (mSingle == null) {
            synchronized (RetrofitMangerTack.class) {
                if (mSingle == null) {
                    mSingle = new RetrofitMangerTack();
                }
            }

        }
        return mSingle;
    }

    public void put(Class classes, Call call) {
        List<Call> listDatas = datas.get(classes);
        /**
         * 先判断是否请求是否已在数据集中
         */
        if (listDatas != null && !listDatas.contains(call)) {
            listDatas.add(call);
        } else if (call == null) {
            listDatas = new ArrayList<>();
            listDatas.add(call);
        } else {
            listDatas.add(call);
        }
    }

    /**
     * 结束某个活动下的所有请求
     *
     * @param classes
     */
    public void canclePositionKind(Class classes) {
        List<Call> calls = datas.get(classes);
        if (calls != null && calls.size() > 0) {
            for (Call c : calls) {
                c.cancel();
            }
        }
        datas.remove(classes);
    }

    public void cancleAll() {
        Set<Class> classes = datas.keySet();
        for (Class c : classes) {
            List<Call> calls = datas.get(c);
            for (Call call : calls) {
                call.cancel();
            }
        }
        classes.clear();
    }
}
